package com.onlinemeal.customer.service.impl;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.onlinemeal.customer.dao.CustomerDao;
import com.onlinemeal.customer.po.Customer;
import com.onlinemeal.customer.service.CustomerService;

@Service("customerService")
public class CustomerServiceImpl implements CustomerService {
	@Autowired(required=true)
	@Resource(name="customerDao")
	private CustomerDao customerDao;
	
	@Override
	@Transactional
	public boolean registCustomer(Customer customer) {
		System.out.println("service");
		customerDao.addCustomer(customer);
		return true;
	}
	
	@Override
	@Transactional
	public void active(String code) {
		/**
		 * 1、使用code查询数据库，得到user
		 */
		Customer customer = customerDao.findByCode(code);
		/**
		 * 2、若是User不存在，则说明激活码出错
		 */
		if(customer == null)
			try {
				throw new CustomerException("激活码无效!");
			} catch (CustomerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		/**
		 * 3、校验用户的状态是否为未激活状态，如果已经激活，说明是二次激活，抛出异常
		 */
		if(customer.getState().equals("1"))
			try {
				throw new CustomerException("您已经激活过了，请不要重新激活！");
			} catch (CustomerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		/**
		 * 4、修改用户状态
		 */
		customerDao.updateState(customer.getUid(), "1");
	}
	
	@Override
	public int loginCustomer(Customer customer) {
		/**
		 * tag标示：
		 * 0代表输入错误的用户名或者密码；
		 * 1：代表没有激活；
		 * 2：代表正常登陆成功
		 */
		Customer customer_find = null; 
		customer_find = customerDao.findByUsernameAndPassword(customer);
		System.out.println("=============Service============="+customer);
		
		if (customer_find == null) {
			return 0;
		} else if(customer_find!=null && customer_find.getState().equals("0")) {
			return 1;
		} else {
			return 2;
		}
	}

}
